<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Address;
use app\model\BlessingOrder;
use app\model\Product;
use app\model\ProductOrder;
use app\model\Temple;
use think\facade\Db;

/**
 * @extends Service<ProductOrderService>
 */
class ProductOrderService extends Service
{

    const STATUS = [
        1 => '待支付',
        2 => '已支付',
        3 => '已取消',
    ];

    public function list($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['status']) && $searchQuery['status'] != '') {
            $w[] = ['status', '=', $searchQuery['status']];
        }
        if (!empty($searchQuery['member_id']) && $searchQuery['member_id'] != '') {
            $w[] = ['member_id', '=', $searchQuery['member_id']];
        }
        if (!empty($searchQuery['return_status']) && $searchQuery['return_status'] != '') {
            $w[] = ['return_status', 'in', explode(',', $searchQuery['return_status'])];
        }
        if (!empty($searchQuery['order_no']) && $searchQuery['order_no'] != '') {
            $w[] = ['order_no', '=', $searchQuery['order_no']];
        }
        if (!empty($searchQuery['paytimeValues'])) {
            if (!is_array($searchQuery['paytimeValues'])) {
                $timeValues = json_decode($searchQuery['paytimeValues']);
            } else {
                $timeValues = $searchQuery['paytimeValues'];
            }
            $w[] = ['pay_time', 'between', $timeValues];
        }
        if (!empty($searchQuery['timeValues'])) {
            if (!is_array($searchQuery['timeValues'])) {
                $timeValues = json_decode($searchQuery['timeValues']);
            } else {
                $timeValues = $searchQuery['timeValues'];
            }
            $w[] = ['create_time', 'between', $timeValues];
        }
        $map = ProductOrder::where($w)->page($page, $limit)->order('order_id desc');
        $list = $map->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $product_ids = array_column($list, 'product_id');
            $productList = Product::where('product_id', 'in', $product_ids)->select()->toArray();
            $productList = array_column($productList, null, 'product_id');
            $address_ids = array_column($list, 'address_id');
            $addressList = Address::where('address_id', 'in', $address_ids)->select()->toArray();
            $addressList = array_column($addressList, null, 'address_id');
            foreach ($list as &$value) {
                if (!empty($productList[$value['product_id']]['product_img'])) {
                    $value['product_img'] = $productList[$value['product_id']]['product_img'];
                } else {
                    $value['product_img'] = '';
                }
                if (!empty($addressList[$value['address_id']])) {
                    $value['address'] = $addressList[$value['address_id']];
                } else {
                    $value['address'] = '';
                }
            }
        }
        return [
            'total' => $map->count(),
            'list' => $list,
        ];
    }

    public function getExportList($searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['status']) && $searchQuery['status'] != '') {
            $w[] = ['status', '=', $searchQuery['status']];
        }
        if (!empty($searchQuery['member_id']) && $searchQuery['member_id'] != '') {
            $w[] = ['member_id', '=', $searchQuery['member_id']];
        }
        if (!empty($searchQuery['order_no']) && $searchQuery['order_no'] != '') {
            $w[] = ['order_no', '=', $searchQuery['order_no']];
        }
        $list = ProductOrder::where($w)->select();
        if (!empty($list)) {
            $list = $list->toArray();
            $address_ids = array_column($list, 'address_id');
            $addressList = Address::where('address_id', 'in', $address_ids)->select()->toArray();
            foreach ($list as &$v) {
                $v['name'] = $v['address_id'] && !empty($addressList[$v['address_id']]['name']) ? $addressList[$v['address_id']]['name'] : '';
                $v['address'] = $v['address_id'] && !empty($addressList[$v['address_id']]['address']) ? $addressList[$v['address_id']]['address'] : '';
                $v['mobile'] = $v['address_id'] && !empty($addressList[$v['address_id']]['mobile']) ? $addressList[$v['address_id']]['mobile'] : '';
                $v['status_name'] = self::STATUS[$v['status']];
            }
        }
        return [
            'list' => $list,
        ];
    }

    public function save($data, $member_id)
    {
        $product = Product::where(
            'product_id', '=', $data['product_id']
        )->find();
        if (!$product) {
            throw new BusinessException('商品不存在');
        }
        $Address = Address::where(['address_id' => $data['address_id'], 'member_id' => $member_id])->find();
        if (!$Address) {
            throw new BusinessException('请选择地址');
        }
        $freight = 10;
        Db::startTrans();
        try {
            $order_no = 'OD' . time() . rand(1000, 9999) . $member_id;
            $rs = $productOrder = ProductOrder::create([
                'create_time' => date('Y-m-d H:i:s', time()),
                'order_no' => $order_no,
                'product_name' => $product['product_name'],
                'price' => $product['product_price'] + $freight,
                'product_price' => $product['product_price'],
                'freight' => $freight,
                'status' => 1,
                'product_id' => $data['product_id'],
                'address_id' => $data['address_id'] ?: 0,
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'member_id' => $member_id,
            ]);
            if (!$productOrder->order_id) {
                throw new BusinessException('订单创建失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return $rs;
    }

    public function checkReturn($data, $order_id)
    {
        $w = ['order_id' => $order_id];
        $info = ProductOrder::where($w)->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        if ($info->return_status !== 1) {
            throw new BusinessException('订单无需审核售后');
        }
        $info->save(['return_status' => $data['return_status'], 'refuse_reason' => $data['refuse_reason']]);
    }

    public function info($order_id, $member_id = null)
    {
        $w = ['order_id' => $order_id];
        if ($member_id) {
            $w['member_id'] = $member_id;
        }
        $info = ProductOrder::where($w)->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        $product = Product::where([
            'product_id' => $info['product_id']
        ])->find();
        if ($info['address_id']) {
            $address = Address::where([
                'address_id' => $info['address_id']
            ])->find();
        }
        $info['product_img'] = !empty($product['product_img']) ? $product['product_img'] : '';
        $info['address'] = !empty($address) ? $address : '';
        return $info;
    }

    public function cancelOrder($order_id, $member_id)
    {
        $info = ProductOrder::where([
            'status' => 1, 'order_id' => $order_id, 'member_id' => $member_id,
        ])->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        $info->save(['status' => 3, 'cancel_time' => date('Y-m-d H:i:s', time())]);
        return $info;
    }

    public function delOrder($order_id, $member_id)
    {
        $info = ProductOrder::where([
            'status' => 3, 'order_id' => $order_id, 'member_id' => $member_id,
        ])->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        $info->delete();
        return $info;
    }

    public function afterSale($order_id, $member_id, $data)
    {
        $info = ProductOrder::where([
            'status' => 2, 'order_id' => $order_id, 'member_id' => $member_id,
        ])->find();
        if (!$info) {
            throw new BusinessException('订单不存在');
        }
        if (!empty($data['return_no'])) {
            $info->save(['return_no' => $data['return_no']]);
            return true;
        }

        if ($info->return_status > 0) {
            throw new BusinessException('该订单已发起售后');
        }
        $map = [
            'apply_type' => $data['apply_type'] ?: 0,
            'refund_amount' => $data['refund_amount'] ?: 0,
            'return_status' => 1,
            'describe' => !empty($data['describe']) ? $data['describe'] : '',
            'reason' => !empty($data['reason']) ? $data['reason'] : '',
            'proof' => !empty($data['proof']) ? $data['proof'] : '',
            'mobile' => !empty($data['mobile']) ? $data['mobile'] : '',
            'change_product_id' => $data['product_id'] ?: 0,
        ];
        $info->save($map);
        return $info;
    }
}